package com.google.code.sip.ucenter.ws.resources;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.ws.Action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.code.sip.ucenter.model.Friend;
import com.google.code.sip.ucenter.model.FriendGroup;
import com.google.code.sip.ucenter.model.User;
import com.google.code.sip.ucenter.service.FriendGroupManager;
import com.google.code.sip.ucenter.service.FriendManager;
import com.google.code.sip.ucenter.service.UserManager;
import com.google.code.sip.ucenter.ws.WSResponse;
import com.google.code.sip.ucenter.ws.WSResponseStatus;
import com.google.code.sip.ucenter.ws.dto.FriendDto;
import com.google.code.sip.ucenter.ws.dto.FriendGroupDto;
import com.sun.jersey.spi.resource.Singleton;

@Component
@Path("/friend")
@Singleton
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class FriendResource extends AbstractResource {
	private static final Logger logger = LoggerFactory
			.getLogger(FriendResource.class);
	@Autowired
	private FriendManager friendMananger;

	@Autowired
	private UserManager userManager;

	@Autowired
	private FriendGroupManager friendGroupManager;

	@POST
	@Action
	@Path("/list")
	public WSResponse<FriendDto> getFriends(@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<FriendDto>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			List<Friend> friendList = friendMananger.getFriends(user);
			WSResponse<FriendDto> wsResponse = new WSResponse<FriendDto>();
			if (friendList.size() != 0) {
				FriendGroup friendGroup = null;
				User friendUser = null;
				FriendDto friendDto = null;
				for (Friend friend : friendList) {
					friendDto = new FriendDto();

					friendGroup = friendGroupManager.getFriendGroup(friend
							.getFriendGroup().getId());
					friendDto.setFriendGroupId(friendGroup.getId());
					friendDto.setFriendGroupName(friendGroup.getName());

					friendUser = userManager
							.getUser(friend.getFriend().getId());
					friendDto.setFriendId(friendUser.getId());
					friendDto.setFriendLoginName(friendUser.getUsername());
					friendDto.setFriendNickName(friendUser.getNickName());

					friendDto.setId(friend.getId());
					friendDto.setUserId(friend.getUser().getId());
					friendDto.setCreatedDate(friend.getCreatedDate());

					wsResponse.addResult(friendDto);
				}
			}

			return wsResponse;
		} catch (RuntimeException e) {
			logger.error("called getFriends method error userId:" + userId, e);
			return new WSResponse<FriendDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/listByGroup")
	public WSResponse<FriendDto> getFriendsByGroup(
			@FormParam("groupId") String groupId) {
		assert (null != groupId) : "groupId cann't be null.";
		WSResponse<FriendDto> wsResponse = new WSResponse<FriendDto>();
		try {
			FriendGroup group = friendGroupManager.getFriendGroup(groupId);
			if (group == null) {
				return new WSResponse<FriendDto>(new WSResponseStatus(-1,
						"该好友组不存在！。"));
			}
			List<Friend> friendList = friendMananger.getFriends(group);
			if (friendList.size() != 0) {
				User friendUser = null;
				FriendDto friendDto = null;
				for (Friend friend : friendList) {
					friendDto = new FriendDto();
					friendDto.setFriendGroupId(group.getId());
					friendDto.setFriendGroupName(group.getName());

					friendUser = userManager
							.getUser(friend.getFriend().getId());
					friendDto.setFriendId(friendUser.getId());
					friendDto.setFriendLoginName(friendUser.getUsername());
					friendDto.setFriendNickName(friendUser.getNickName());

					friendDto.setId(friend.getId());
					friendDto.setUserId(friend.getUser().getId());
					friendDto.setCreatedDate(friend.getCreatedDate());

					wsResponse.addResult(friendDto);
				}
			}
			return wsResponse;
		} catch (RuntimeException e) {
			logger.error("called getFriendsByGroup method error groupId:"
					+ groupId, e);
			return new WSResponse<FriendDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/count")
	public WSResponse<String> getFriendsCount(@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			int friendsCount = friendMananger.getFriendsCount(user);
			return new WSResponse<String>(String.valueOf(friendsCount));
		} catch (RuntimeException e) {
			logger.error(
					"called getFriendsCount method error userId:" + userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/isFriend")
	public WSResponse<String> isFriend(@FormParam("userId") String userId,
			@FormParam("friendId") String friendId) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != friendId) : "friendId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			User friendUser = userManager.getUser(friendId);
			if (user == null || friendUser == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			boolean isFriend = friendMananger.isFriend(user, friendUser);
			return new WSResponse<String>(String.valueOf(isFriend));
		} catch (RuntimeException e) {
			logger.error("called isFriend method error userId:" + userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/groups")
	public WSResponse<FriendGroupDto> getFriendGroups(
			@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<FriendGroupDto>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			List<FriendGroup> friendGroupList = friendGroupManager
					.getFriendGroups(user);
			WSResponse<FriendGroupDto> wsResponse = new WSResponse<FriendGroupDto>();
			if (friendGroupList.size() != 0) {
				FriendGroupDto friendGroupDto = null;
				for (FriendGroup friendGroup : friendGroupList) {
					friendGroupDto = new FriendGroupDto();
					BeanUtils.copyProperties(friendGroup, friendGroupDto);
					friendGroupDto.setUserId(friendGroup.getUser().getId());
					wsResponse.addResult(friendGroupDto);
				}
			}
			return wsResponse;
		} catch (RuntimeException e) {
			logger.error(
					"called getFriendGroups method error userId:" + userId, e);
			return new WSResponse<FriendGroupDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/add")
	public WSResponse<String> addFriend(@FormParam("userId") String userId,
			@FormParam("friendId") String friendId,
			@FormParam("groupId") String friendGroupId,
			@FormParam("remark") String remark) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != friendId) : "friendId cann't be null.";
		assert (null != friendGroupId) : "friendGroupId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			User friendUser = userManager.getUser(friendId);
			if (user == null || friendUser == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户或好友不存在。"));
			}

			FriendGroup friendGroup = friendGroupManager
					.getFriendGroup(friendGroupId);
			if (friendGroup == null
					&& friendGroupManager.getDefaultFriendGroup(user) == null) {
				// 如果好友组都找不到就创建一组默认组
				friendGroupManager.createdCommonGroups(user);
				// 如果没有找到好友组就放到默认组里面
				friendGroup = friendGroupManager.getDefaultFriendGroup(user);
			}
			friendMananger.addFriend(user, friendUser, friendGroup, remark);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called addFriend method error userId:" + userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/delete")
	public WSResponse<String> deleteFriend(@FormParam("userId") String userId,
			@FormParam("friendId") String friendId) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != friendId) : "friendId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			User friendUser = userManager.getUser(friendId);
			if (user == null || friendUser == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户或好友不存在。"));
			}
			friendMananger.deleteFriend(user, friendUser);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger
					.error("called deleteFriend method error userId:" + userId,
							e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/move")
	public WSResponse<String> moveFriend(@FormParam("userId") String userId,
			@FormParam("friendId") String friendId,
			@FormParam("newGroupId") String newGroupId) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != friendId) : "friendId cann't be null.";
		assert (null != newGroupId) : "newGroupId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			User friendUser = userManager.getUser(friendId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"该好友不存在。"));
			}
			Friend friend = friendMananger.getFriend(user, friendUser);
			if (friend == null) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"好友关系不存在。"));
			}
			FriendGroup newFriendGroup = friendGroupManager
					.getFriendGroup(newGroupId);
			if (newFriendGroup == null) {
				return new WSResponse<String>(new WSResponseStatus(-4,
						"目标好友组不存在。"));
			}
			friendMananger.moveFriend(friend, newFriendGroup);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called moveFriend method error userId:" + userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/addGroup")
	public WSResponse<String> addFriendGroup(
			@FormParam("userId") String userId,
			@FormParam("groupName") String groupName,
			@FormParam("description") String description) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != groupName) : "groupName cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在。"));
			}
			friendGroupManager.addFriendGroup(user, groupName, description);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called addFriendGroup method error userId:" + userId,
					e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/updateGroup")
	public WSResponse<String> updateFriendGroupName(
			@FormParam("groupId") String groupId,
			@FormParam("groupName") String groupName) {
		assert (null != groupId) : "groupId cann't be null.";
		assert (null != groupName) : "groupName cann't be null.";
		try {
			FriendGroup friendGroup = friendGroupManager
					.getFriendGroup(groupId);
			if (friendGroup == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该好友组不存在。"));
			}
			friendGroupManager.updateGroupName(friendGroup, groupName);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called updateFriendGroupName method error groupName:"
					+ groupName, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Action
	@Path("/deleteGroup")
	public WSResponse<String> deleteFriendGroup(
			@FormParam("groupId") String groupId) {
		assert (null != groupId) : "groupId cann't be null.";
		try {
			FriendGroup friendGroup = friendGroupManager
					.getFriendGroup(groupId);
			if (friendGroup == null) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该好友组不存在。"));
			}
			friendGroupManager.deleteFriendGroup(friendGroup);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called deleteFriendGroup method error groupId:"
					+ groupId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}
}
